package xyz.weizhi.tanhua.appserver.service;

import cn.hutool.core.collection.CollUtil;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.stereotype.Service;
import xyz.weizhi.tanhua.appserver.interceptor.UserHolder;
import xyz.weizhi.tanhua.dubbo.api.CommentsApi;
import xyz.weizhi.tanhua.dubbo.api.MovementApi;
import xyz.weizhi.tanhua.dubbo.api.UserInfoApi;
import xyz.weizhi.tanhua.model.domain.UserInfo;
import xyz.weizhi.tanhua.model.enums.CommentType;
import xyz.weizhi.tanhua.model.mongo.Comment;
import xyz.weizhi.tanhua.model.mongo.Movement;
import xyz.weizhi.tanhua.model.vo.CommentVo;
import xyz.weizhi.tanhua.model.vo.PageResult;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author milian
 * @Date 2021/10/27 0027 20:29
 */
@Service
public class CommentsService {
    @DubboReference
    private CommentsApi commentsApi;
    @DubboReference
    private MovementApi movementApi;
    @DubboReference
    private UserInfoApi userInfoApi;
    public PageResult comments(String movementId, Integer page, Integer pagesize) {
        // 调用api查询评论信息
        PageResult pageResult = commentsApi.findComments(movementId, CommentType.COMMENT, page, pagesize);
        List<Comment> list = (List<Comment>) pageResult.getItems();
        // 判断list集合是否存在
        if (CollUtil.isEmpty(list)){
            return new PageResult();
        }
        // 获取评论人id
        List<Long> userIds = CollUtil.getFieldValues(list, "userId", Long.class);
        Map<Long, UserInfo> userInfoMap = userInfoApi.findByIds(userIds, null);
        ArrayList<CommentVo> vos = new ArrayList<>();
        for (Comment comment : list) {
            UserInfo userInfo = userInfoMap.get(comment.getUserId());
            CommentVo vo = CommentVo.init(userInfo, comment);
            vos.add(vo);
        }
        pageResult.setItems(vos);
        return pageResult;
    }

    public void pubulish(String movementId,String comment) {
        // 调用api查询动态信息

        Comment commentObj = new Comment();
        commentObj.setUserId(UserHolder.getId());
        commentObj.setPublishId(new ObjectId(movementId));
        commentObj.setCommentType(CommentType.COMMENT.getType());
        commentObj.setContent(comment);
        commentObj.setCreated(System.currentTimeMillis());
        // 调用接口保存评论
        Integer newCount = commentsApi.save(commentObj);
    }
}
